<template>
  <div>
    <FormPanel ref="form" :list="formList" formType="add" :isSubmitBtn="false" labelWidth="90" @formChange="changeHandle" />
    <FilterTable ref="basetable" :columns="columns" :onSyncTableData="tablechangeFun" :onColumnsChange="columns => (this.columns = columns)" columnsRef="partPartInventoryAdjustInventoryNewPartInfo" />
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <p class="test">说明:成本价不含税</p>
      <el-button @click="closeDrawer(1)">取 消</el-button>
      <el-button type="primary" @click="closeDrawer(2)">保 存</el-button>
    </div>
  </div>
</template>
<script>
import {
  newBuild,
  getpartStocksList,
  getDealertCode,
  getfindStorageCode,
  getquerypartGroupCodes,
  getpartInfos,
  querypartInfo,
  getStockQuantity,
  getPosition,
  savePartInfo,
  save,
  queryUsableLocations
} from '@/api/part/inventoryManager/inventoryManager/index';
import { dictionary } from '@/utils/dictMixin';
import pinyin, { STYLE_FIRST_LETTER } from '@/components/Pinyin/index';
import { log } from 'util';
import { getBrand } from '@/api/repair/basicParameters';
import { queryUnitCode, queryPartInfos } from '@/api/part/partInfo';
export default {
  mixins: [dictionary],
  props: {
    formData: Object
  },
  data() {
    this.commitData = null;
    this.basetable = null;
    return {
      formList: this.createFrom(),
      fetchParams: {
        dmsFuncId: 30101500,
        _: 1566905683555
      },
      partInfoList: [],
      columns: this.createTable(),
      locationLists: [],
      formDataList: {},
      flag: null
    };
  },
  created() {
    this.getBrand();
    this.queryUnitCode();
    this.getDictlist();
    this.formList.find(x => x.fieldName === 'storageCode').initialValue = this.formData.STORAGE_CODE;
    this.formList.find(x => x.fieldName === 'partNo').initialValue = this.formData.partNo;
    this.formList.find(x => x.fieldName === 'storagePositionCode').initialValue = this.formData.STORAGE_POSITION_CODE;
    this.formList.find(x => x.fieldName === 'partName').initialValue = this.formData.PART_NAME;
    this.queryPartInfos();
  },
  mounted() {
    this.basetable = this.$refs.basetable.$refs.pageTable;
  },
  methods: {
    // 如果有明细信息获取明细信息的接口
    async queryPartInfos() {
      const res = await queryPartInfos({ partNo: this.formData.partNo });
      console.log(res.data.rows, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa');

      // 判断  partNo 是否和查询的一致
      if (res.data.rows.length > 0) {
        res.data.rows.forEach((x, index) => {
          if (x.partNo == this.formData.partNo) {
            this.formList.forEach(item => {
              // if (item.fieldName === x.fieldName) {
              item.initialValue = res.data.rows[index][item.fieldName];
              //  }
            });
          }
        });
      }
      if (
        this.formList.find(x => x.fieldName === 'partName').initialValue == null ||
        this.formList.find(x => x.fieldName === 'partName').initialValue == '' ||
        this.formList.find(x => x.fieldName === 'partName').initialValue == undefined
      ) {
        this.formList.find(x => x.fieldName === 'partName').initialValue = this.formData.PART_NAME;
      }
      this.formList.find(x => x.fieldName === 'storageCode').initialValue = this.formData.STORAGE_CODE;
      this.formList.find(x => x.fieldName === 'partNo').initialValue = this.formData.partNo;
      this.formList.find(item => item.fieldName == 'spellCode').initialValue = pinyin(this.formList.find(x => x.fieldName === 'partName').initialValue, { style: STYLE_FIRST_LETTER })
        .flat()
        .join('');
      this.queryEmptyLocation(true, true);
    },
    // 单位下拉框
    async queryUnitCode() {
      const res3 = await queryUnitCode();
      this.formList.find(item => item.fieldName == 'unitCode').itemList = res3.data.map(x => ({ text: x.UNIT_NAME, value: x.UNIT_CODE }));
    },
    // 品牌下拉框获取
    async getBrand() {
      const res = await getBrand();
      this.formList.find(x => x.fieldName === 'brand').itemList = res.data.map(x => ({ text: x.BRAND_NAME, value: x.BRAND_CODE + '' }));
      this.formList.find(x => x.fieldName === 'brand').initialValue = res.data.find(item => item.BRAND_NAME == '奥迪').BRAND_CODE + '';
    },
    // 选择仓库之后得回调
    storageChange(val) {
      console.log('表单数据：', this.formDataList);
      if (this.formDataList.partNo == null || this.formDataList.partNo == '') {
        // this.$notify.warning({ title: '提示信息', message: '请填写配件代码' });
      } else {
        this.formDataList.storageCode = val;
        this.queryEmptyLocation(true, true);
      }
    },
    // 选择仓库配件之后的回调,更新库存信息(这里有问题)
    async queryEmptyLocation(flag, val) {
      // if (!val) {
      this.formDataList.storageCode = this.formList.find(item => item.fieldName == 'storageCode').initialValue;
      // }
      this.formDataList.partNo = this.formList.find(item => item.fieldName == 'partNo').initialValue;
      // if (this.formDataList.storageCode == null || this.formDataList.storageCode == '') {
      //   this.$notify.warning({ title: '消息提示', message: '请先填写仓库信息' });
      //   return;
      // }
      let res = null;
      // if (flag) {
      //   res = await queryUsableLocations({ storageCode: this.formDataList.storageCode, partNo: this.formDataList.partNo });
      // } else {
      //   res = await getPosition({ storageCode: this.formDataList.storageCode });
      // }
      res = await queryUsableLocations({ storageCode: this.formDataList.storageCode, partNo: this.formDataList.partNo });
      if (res.resultCode == 200) {
        // console.log(res.data[0].error);
        if (res.data[0].error) {
          this.$notify.warning({ title: '错误提示', message: res.data[0].error });
        } else {
          this.formList.find(item => item.fieldName === 'storagePositionCode').itemList = res.data.map(x => ({ text: x.storagePositionCode, value: x.storagePositionCode }));
        }
      }
    },
    createFrom() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          disabled: true,
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          change: this.storageChange
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        // {
        //   type: 'INPUT',
        //   label: '税率',
        //   fieldName: 'taxRate',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '成本单价',
        //   fieldName: 'costPrice',
        //   disabled: true,
        //   initialValue: '0'
        // },
        {
          type: 'SELECT',
          label: '库位代码',
          fieldName: 'storagePositionCode',
          rules: [{ required: true, message: '请选择库位代码', trigger: 'blur' }],
          itemList: []
        },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '成本金额',
        //   fieldName: 'costAmount',
        //   disabled: true,
        //   initialValue: '0'
        // },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          disabled: true,
          rules: [{ required: true, message: '请输入配件代码', trigger: 'blur' }],
          change: props => {
            this.changePartNo(props);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '库存数量',
          fieldName: 'stockQuantity',
          disabled: true,
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '最新进货价',
          fieldName: 'latestPrice',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          rules: [{ required: true, message: '请输入配件名称', trigger: 'blur' }],
          onInput: e => {
            this.formList.find(item => item.fieldName == 'spellCode').initialValue = pinyin(e, { style: STYLE_FIRST_LETTER })
              .flat()
              .join('');
          },
          change: props => {
            this.changePartName(props);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '锁定量',
          fieldName: 'lockedQuantity',
          disabled: true,
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '建议销售价',
          disabled: true,
          fieldName: 'instructPrice',
          // disabled: true
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '批发价',
          fieldName: 'wholesalesPrice',
          // disabled: true
          initialValue: '0'
        },
        {
          type: 'SELECT',
          label: '单位',
          fieldName: 'unitCode',
          itemList: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '安全库存',
          fieldName: 'safeStock',
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '销售限价',
          fieldName: 'limitPrice',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '拼音代码',
          fieldName: 'spellCode',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '最小库存',
          fieldName: 'minStock',
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '索赔价',
          fieldName: 'claimPrice',
          // disabled: true,
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '最大库存',
          fieldName: 'maxStock',
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '网点价',
          fieldName: 'maintainPrice',
          disabled: true,
          initialValue: '0'
          // render: props => {
          //   return <span>{this.formList.find(item => item.fieldName == 'salesPrice')}.initialValue</span>;
          // }
        },
        {
          type: 'SELECT',
          label: '九大类',
          fieldName: 'partMainType',
          itemList: this.createDictList('8094'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '最小包装数',
          fieldName: 'minPackage',
          disabled: true,
          initialValue: '0'
        },
        {
          type: 'INPUT_NUMBER',
          label: '终端建议零售价格',
          fieldName: 'insurancePrice',
          initialValue: '0'
        },
        {
          type: 'SELECT',
          label: '配件类别',
          fieldName: 'partGroupCode',
          itemList: this.createDictList('8075'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '替代配件',
          fieldName: 'optionNo',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '销售价',
          fieldName: 'salesPrice',
          initialValue: '0',
          onInput: e => {
            this.formList.find(item => item.fieldName == 'maintainPrice').initialValue = e;
          }
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark'
          // initialValue: ''
        }
      ];
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '年度',
          dataIndex: 'YEAR',
          sorter: true,
          filter: true
        },
        {
          title: '月度',
          dataIndex: 'month',
          sorter: true,
          filter: true
        },
        {
          title: '出库数量',
          dataIndex: 'outQuantity',
          sorter: true,
          filter: true
        },
        {
          title: '入库数量',
          dataIndex: 'inQuantity',
          sorter: true,
          filter: true
        }
      ];
    },
    async getStorage() {
      const res = await getfindStorageCode();
      this.formList.find(item => item.fieldName === 'storageCode').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      // this.form[0].itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    changeHandle(val) {
      // this.$refs.form.SUBMIT_FORM();
      this.commitData = val;
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('cancel', false);
        // let row = {}
        // row = this.formData
        // this.$emit('addChange',row);
      } else {
        this.commitData = this.$refs.form.SUBMIT_FORM();
        this.commitData['flg'] = 'A';
        let obj = { dmstable: [this.commitData], dmsTable: [this.commitData] };
        // obj = JSON.parse(JSON.stringify(obj));
        let res = await save(obj);
        if (res.resultCode == '200') {
          this.$notify.success({ title: '提示信息', message: '保存成功' });
          let row = Object.assign({}, this.formData, this.commitData);
          row.STORAGE_CODE = this.formList.find(x => x.fieldName === 'storageCode').initialValue;
          row.PART_NO = this.formList.find(x => x.fieldName === 'partNo').initialValue;
          row.UNIT_CODE = this.formList.find(x => x.fieldName === 'unitCode').initialValue;
          row.PART_NAME = this.formList.find(x => x.fieldName === 'partName').initialValue;
          row.STORAGE_POSITION_CODE = this.formList.find(x => x.fieldName === 'storagePositionCode').initialValue;
          row.partGroupCode = this.formList.find(x => x.fieldName === 'partGroupCode').initialValue;
          row.partMainType = this.formList.find(x => x.fieldName === 'partMainType').initialValue;
          row.closeShow = false;
          this.formList
            .find(item => item.fieldName == 'unitCode')
            .itemList.forEach(x => {
              if (row.UNIT_CODE == x.value) {
                row.UNIT_NAME = x.text;
              }
            });
          this.formList
            .find(item => item.fieldName === 'storageCode')
            .itemList.forEach(x => {
              if (x.value == row.STORAGE_CODE) {
                row.STORAGE_NAME = x.text;
              }
            });
          this.$emit('showOrder', row);
        }
      }
    },
    // 获取数据字典
    async getDictlist() {
      // 获取
      let res = (await getfindStorageCode(this.fetchParams)).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.formList.find(item => item.fieldName === 'storageCode').itemList = res;
      // this.formList[0].itemList = res;
      // console.log(res, 'res');
      let res2 = await getpartInfos(this.fetchParams);
      this.partInfoList = res2;
      let res1 = (await getquerypartGroupCodes(this.fetchParams)).data.map(x => ({ text: x.PART_MODEL_GROUP_NAME, value: x.PART_MODEL_GROUP_CODE }));
    },
    async changePartNo(val) {
      if (!val) {
        this.$notify.warning({ title: '提示信息', message: '请先填写配件代码' });
        retrun;
      }
      let storageCode = this.formList.find(item => item.fieldName === 'storageCode').initialValue;
      if (storageCode == '' || storageCode == null) {
        // if (this.formList[0].initialValue == '' || this.formList[0].initialValue == null) {
        this.$notify.warning({ title: '提示信息', message: '请先填写' + this.formList[0].label });
      }
      let res = await querypartInfo(val);
      if (res.resultCode == '200') {
        this.queryEmptyLocation(true);
      }
      if (res.data.length != 0) {
        let res4 = res.data[0];
        res4.storageCode = storageCode;
        this.formList.forEach(x => {
          x.initialValue = res4[x.fieldName];
        });
        let res2 = await getStockQuantity(val, storageCode);
        this.basetable.EXECUTE_INSERT(res2.data);
      } else {
        console.log('该配件不存在需要添加新的配件信息');
        this.flag = 'A';
        this.queryEmptyLocation(false);
        return this.$notify.warning({ title: '提示信息', message: '该配件不存在需要，需要添加新的配件信息' });
      }
    },
    tablechangeFun() {},
    changePartName(val) {
      console.log('哈哈', val);
      let is = false;
      for (let i = 0; i < this.partInfoList.length; i++) {
        if (this.partInfoList[i].value == val) {
          is = true;
        }
      }
      if (is) {
        this.$confirm('配件代码重复是否确定？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {
            this.formList.find(item => item.fieldName === 'partName').initialValue = '';
          });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.test {
  text-align: left;
  color: red;
  display: block;
  float: left;
}
</style>
